home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Browsers, Managers & Extensions / Mozilla Weave 0.2.7 / latest-weave.xpi / modules / engines / tabs.js < prev   
Text File  |  2008-08-04  |  10KB  |  285 lines

  1. /* ***** BEGIN LICENSE BLOCK *****
  2.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3.  *
  4.  * The contents of this file are subject to the Mozilla Public License Version
  5.  * 1.1 (the "License"); you may not use this file except in compliance with
  6.  * the License. You may obtain a copy of the License at
  7.  * http://www.mozilla.org/MPL/
  8.  *
  9.  * Software distributed under the License is distributed on an "AS IS" basis,
  10.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11.  * for the specific language governing rights and limitations under the
  12.  * License.
  13.  *
  14.  * The Original Code is Bookmarks Sync.
  15.  *
  16.  * The Initial Developer of the Original Code is Mozilla.
  17.  * Portions created by the Initial Developer are Copyright (C) 2008
  18.  * the Initial Developer. All Rights Reserved.
  19.  *
  20.  * Contributor(s):
  21.  *  Myk Melez <myk@mozilla.org>
  22.  *
  23.  * Alternatively, the contents of this file may be used under the terms of
  24.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  25.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  26.  * in which case the provisions of the GPL or the LGPL are applicable instead
  27.  * of those above. If you wish to allow use of your version of this file only
  28.  * under the terms of either the GPL or the LGPL, and not to allow others to
  29.  * use your version of this file under the terms of the MPL, indicate your
  30.  * decision by deleting the provisions above and replace them with the notice
  31.  * and other provisions required by the GPL or the LGPL. If you do not delete
  32.  * the provisions above, a recipient may use your version of this file under
  33.  * the terms of any one of the MPL, the GPL or the LGPL.
  34.  *
  35.  * ***** END LICENSE BLOCK ***** */
  36.  
  37. const EXPORTED_SYMBOLS = ['TabEngine'];
  38.  
  39. const Cc = Components.classes;
  40. const Ci = Components.interfaces;
  41. const Cu = Components.utils;
  42.  
  43. Cu.import("resource://weave/util.js");
  44. Cu.import("resource://weave/async.js");
  45. Cu.import("resource://weave/engines.js");
  46. Cu.import("resource://weave/syncCores.js");
  47. Cu.import("resource://weave/stores.js");
  48. Cu.import("resource://weave/trackers.js");
  49. Cu.import("resource://weave/constants.js");
  50.  
  51. Function.prototype.async = Async.sugar;
  52.  
  53. function TabEngine(pbeId) {
  54.   this._init(pbeId);
  55. }
  56.  
  57. TabEngine.prototype = {
  58.   __proto__: new BlobEngine(),
  59.  
  60.   get name() "tabs",
  61.   get displayName() { return "Tabs"; },
  62.   get logName() "TabEngine",
  63.   get serverPrefix() "user-data/tabs/",
  64.  
  65.   get virtualTabs() {
  66.     let virtualTabs = {};
  67.     let realTabs = this._store.wrap();
  68.  
  69.     for (let profileId in this._file.data) {
  70.       let tabset = this._file.data[profileId];
  71.       for (let guid in tabset) {
  72.         if (!(guid in realTabs) && !(guid in virtualTabs)) {
  73.           virtualTabs[guid] = tabset[guid];
  74.           virtualTabs[guid].profileId = profileId;
  75.         }
  76.       }
  77.     }
  78.     return virtualTabs;
  79.   },
  80.  
  81.   get _store() {
  82.     let store = new TabStore();
  83.     this.__defineGetter__("_store", function() store);
  84.     return this._store;
  85.   },
  86.  
  87.   get _tracker() {
  88.     let tracker = new TabTracker(this);
  89.     this.__defineGetter__("_tracker", function() tracker);
  90.     return this._tracker;
  91.   }
  92.  
  93. };
  94.  
  95. function TabStore() {
  96.   this._init();
  97. }
  98. TabStore.prototype = {
  99.   __proto__: new Store(),
  100.   _logName: "TabStore",
  101.  
  102.   get _sessionStore() {
  103.     let sessionStore = Cc["@mozilla.org/browser/sessionstore;1"].
  104.                getService(Ci.nsISessionStore);
  105.     this.__defineGetter__("_sessionStore", function() sessionStore);
  106.     return this._sessionStore;
  107.   },
  108.  
  109.   _createCommand: function TabStore__createCommand(command) {
  110.     this._log.debug("_createCommand: " + command.GUID);
  111.  
  112.     if (command.GUID in this._virtualTabs || command.GUID in this._wrapRealTabs())
  113.       throw "trying to create a tab that already exists; id: " + command.GUID;
  114.  
  115.     // Don't do anything if the command isn't valid (i.e. it doesn't contain
  116.     // the minimum information about the tab that is necessary to recreate it).
  117.     if (!this.validateVirtualTab(command.data)) {
  118.       this._log.warn("could not create command " + command.GUID + "; invalid");
  119.       return;
  120.     }
  121.  
  122.     // Cache the tab and notify the UI to prompt the user to open it.
  123.     this._virtualTabs[command.GUID] = command.data;
  124.     this._os.notifyObservers(null, "weave:store:tabs:virtual:created", null);
  125.   },
  126.  
  127.   /**
  128.    * Serialize the current state of tabs.
  129.    */
  130.   wrap: function TabStore_wrap() {
  131.     let items = {};
  132.  
  133.     let session = this._json.decode(this._sessionStore.getBrowserState());
  134.  
  135.     for (let i = 0; i < session.windows.length; i++) {
  136.       let window = session.windows[i];
  137.       // For some reason, session store uses one-based array index references,
  138.       // (f.e. in the "selectedWindow" and each tab's "index" properties), so we
  139.       // convert them to and from JavaScript's zero-based indexes as needed.
  140.       let windowID = i + 1;
  141.  
  142.       for (let j = 0; j < window.tabs.length; j++) {
  143.         let tab = window.tabs[j];
  144.  
  145.     // The session history entry for the page currently loaded in the tab.
  146.     // We use the URL of the current page as the ID for the tab.
  147.     let currentEntry = tab.entries[tab.index - 1];
  148.     if (!currentEntry || !currentEntry.url) {
  149.       this._log.warn("_wrapRealTabs: no current entry or no URL, can't " +
  150.                          "identify " + this._json.encode(tab));
  151.       continue;
  152.     }
  153.  
  154.     let tabID = currentEntry.url;
  155.  
  156.         // Only sync up to 10 back-button entries, otherwise we can end up with
  157.         // some insanely large snapshots.
  158.         tab.entries = tab.entries.slice(tab.entries.length - 10);
  159.  
  160.         // The ID property of each entry in the tab, which I think contains
  161.         // nsISHEntry::ID, changes every time session store restores the tab,
  162.         // so we can't sync them, or we would generate edit commands on every
  163.         // restart (even though nothing has actually changed).
  164.         for (let k = 0; k < tab.entries.length; k++) {
  165.             delete tab.entries[k].ID;
  166.         }
  167.  
  168.     items[tabID] = {
  169.           // Identify this item as a tab in case we start serializing windows
  170.           // in the future.
  171.       type: "tab",
  172.  
  173.           // The position of this tab relative to other tabs in the window.
  174.           // For consistency with session store data, we make this one-based.
  175.           position: j + 1,
  176.  
  177.       windowID: windowID,
  178.  
  179.       state: tab
  180.     };
  181.       }
  182.     }
  183.  
  184.     return items;
  185.   },
  186.  
  187.   wipe: function TabStore_wipe() {
  188.     // We're not going to close tabs, since that's probably not what
  189.     // the user wants
  190.   }
  191. };
  192.  
  193. function TabTracker(engine) {
  194.   this._engine = engine;
  195.   this._init();
  196. }
  197. TabTracker.prototype = {
  198.   __proto__: new Tracker(),
  199.  
  200.   _logName: "TabTracker",
  201.  
  202.   _engine: null,
  203.  
  204.   get _json() {
  205.     let json = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);
  206.     this.__defineGetter__("_json", function() json);
  207.     return this._json;
  208.   },
  209.  
  210.   /**
  211.    * There are two ways we could calculate the score.  We could calculate it
  212.    * incrementally by using the window mediator to watch for windows opening/
  213.    * closing and FUEL (or some other API) to watch for tabs opening/closing
  214.    * and changing location.
  215.    *
  216.    * Or we could calculate it on demand by comparing the state of tabs
  217.    * according to the session store with the state according to the snapshot.
  218.    *
  219.    * It's hard to say which is better.  The incremental approach is less
  220.    * accurate if it simply increments the score whenever there's a change,
  221.    * but it might be more performant.  The on-demand approach is more accurate,
  222.    * but it might be less performant depending on how often it's called.
  223.    *
  224.    * In this case we've decided to go with the on-demand approach, and we
  225.    * calculate the score as the percent difference between the snapshot set
  226.    * and the current tab set, where tabs that only exist in one set are
  227.    * completely different, while tabs that exist in both sets but whose data
  228.    * doesn't match (f.e. because of variations in history) are considered
  229.    * "half different".
  230.    *
  231.    * So if the sets don't match at all, we return 100;
  232.    * if they completely match, we return 0;
  233.    * if half the tabs match, and their data is the same, we return 50;
  234.    * and if half the tabs match, but their data is all different, we return 75.
  235.    */
  236.   get score() {
  237.     // The snapshot data is a singleton that we can't modify, so we have to
  238.     // copy its unique items to a new hash.
  239.     let snapshotData = this._engine.snapshot.data;
  240.     let a = {};
  241.  
  242.     // The wrapped current state is a unique instance we can munge all we want.
  243.     let b = this._engine.store.wrap();
  244.  
  245.     // An array that counts the number of intersecting IDs between a and b
  246.     // (represented as the length of c) and whether or not their values match
  247.     // (represented by the boolean value of each item in c).
  248.     let c = [];
  249.  
  250.     // Generate c and update a and b to contain only unique items.
  251.     for (id in snapshotData) {
  252.       if (id in b) {
  253.         c.push(this._json.encode(snapshotData[id]) == this._json.encode(b[id]));
  254.         delete b[id];
  255.       }
  256.       else {
  257.         a[id] = snapshotData[id];
  258.       }
  259.     }
  260.  
  261.     let numShared = c.length;
  262.     let numUnique = [true for (id in a)].length + [true for (id in b)].length;
  263.     let numTotal = numShared + numUnique;
  264.  
  265.     // We're going to divide by the total later, so make sure we don't try
  266.     // to divide by zero, even though we should never be in a state where there
  267.     // are no tabs in either set.
  268.     if (numTotal == 0)
  269.       return 0;
  270.  
  271.     // The number of shared items whose data is different.
  272.     let numChanged = c.filter(function(v) !v).length;
  273.  
  274.     let fractionSimilar = (numShared - (numChanged / 2)) / numTotal;
  275.     let fractionDissimilar = 1 - fractionSimilar;
  276.     let percentDissimilar = Math.round(fractionDissimilar * 100);
  277.  
  278.     return percentDissimilar;
  279.   },
  280.  
  281.   resetScore: function FormsTracker_resetScore() {
  282.     // Not implemented, since we calculate the score on demand.
  283.   }
  284. }
  285.